<?php

declare(strict_types=1);
namespace App\Middleware;



use App\Constants\HttpCode;
use App\Traits\ApiResponseTrait;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\Context;
use HyperfExt\Auth\Annotations\Auth;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JWTAuthMiddleware implements MiddlewareInterface
{

    use ApiResponseTrait;
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        foreach (['jwt', 'token'] as $v) {
            $guard = Context::get('guard');
            $token = false;
            try {
                $token = authJwt($v)->check();
            }
            catch (\Exception $e) {}
            catch (\ErrorException $e) {}
            catch (\Throwable $e) {}
            if ($token) {
                Context::set('guard', $v);
                return $handler->handle($request);
            }
        }
        return $this->response->withStatus(401)->json([
            'code'    => 401,
            'message' => 'Token authentication does not pass !',
        ]);
    }
}